package cn.hema.controller;

import cn.hema.mapper.BookMapper;
import cn.hema.po.Book;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商品的服务控制层
 */
@AllArgsConstructor
@RestController
@Slf4j
public class BookController {

    private final BookMapper bookMapper;

    // 1. 根据ID获取书籍
    @GetMapping("/{id}")
    public ResponseEntity<Book> getBookById(@PathVariable Long id) {
        return bookMapper.findById(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> {
                    log.warn("Book not found: ID={}", id);
                    return ResponseEntity.notFound().build();
                });
    }
    // 添加新书
    @PostMapping
    public ResponseEntity<Book> addBook(@RequestBody Book book) {
        System.out.println("in service" + book);
        bookMapper.addBook(book);
        return ResponseEntity.ok(book);
    }

    // 删除书籍
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteBook(@PathVariable Long id) {
        bookMapper.deleteBook(id);
        return ResponseEntity.noContent().build();
    }

    // 更新书籍信息
    @PutMapping("/{id}")
    public ResponseEntity<Book> updateBook(@PathVariable Long id, @RequestBody Book book) {
        book.setId(id); // 确保ID一致性
        bookMapper.updateBook(book);
        return ResponseEntity.ok(book);
    }

    // 查询所有书籍
    @GetMapping
    public ResponseEntity<List<Book>> getAllBooks() {
        return ResponseEntity.ok(bookMapper.getAllBooks());
    }
}
